package com.jinmdz.fmis.common.util.third;

import com.google.gson.JsonSyntaxException;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.bind.util.ISO8601Utils;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * GsonAdapters 适配器类
 *
 * @author LiCongLu
 * @date 2019-12-19 11:56
 */
public class GsonAdapters {

    /**
     * 基础日期时间适配器
     */
    private static abstract class BaseDateTimeAdapter extends TypeAdapter<Date> {

        /**
         * 创建转化格式
         *
         * @return
         */
        public abstract SimpleDateFormat getFormat();

        @Override
        public void write(JsonWriter jsonWriter, Date date) throws IOException {
            jsonWriter.value(getFormat().format(date));
        }

        @Override
        public Date read(JsonReader in) throws IOException {
            if (in.peek() == JsonToken.NULL) {
                in.nextNull();
                return null;
            } else {
                Date date = this.deserializeToDate(in.nextString());
                return date;
            }
        }

        private Date deserializeToDate(String s) {
            synchronized (getFormat()) {
                try {
                    return getFormat().parse(s);
                } catch (ParseException ignored) {
                }
                try {
                    return getFormat().parse(s);
                } catch (ParseException ignored) {
                }
                try {
                    return ISO8601Utils.parse(s, new ParsePosition(0));
                } catch (ParseException e) {
                    throw new JsonSyntaxException(s, e);
                }
            }
        }
    }

    /**
     * 日期转JSON格式化,格式：yyyy-MM-dd
     */
    public static class DateAdapter extends BaseDateTimeAdapter {
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        @Override
        public SimpleDateFormat getFormat() {
            return sdf;
        }
    }

    /**
     * 日期时间转JSON格式化,格式：yyyy-MM-dd HH:mm:ss
     */
    public static class DateTimeAdapter extends BaseDateTimeAdapter {
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        @Override
        public SimpleDateFormat getFormat() {
            return sdf;
        }
    }

}
